package com.example.haoqisystem.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.example.haoqisystem.Utils.ConstUtil;
import com.example.haoqisystem.entity.Lecture;
import com.example.haoqisystem.entity.Notification;
import com.example.haoqisystem.request.EmailRequest;
import com.example.haoqisystem.request.SendEmailToStudentRequest;
import com.example.haoqisystem.request.CreateWebNoticeRequest;
import com.example.haoqisystem.request.UpdateWebNoticeRequest;
import com.example.haoqisystem.response.BaseResponse;
import com.example.haoqisystem.respository.LectureRepository;
import com.example.haoqisystem.respository.NotificationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.Predicate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@RequiredArgsConstructor(onConstructor_ ={@Autowired} )
@Slf4j
public class NotificationService {

    private final EmailService emailService;
    private final NotificationRepository notificationRepository;
    public final LectureRepository lectureRepository;

    //给学员发送邮件
    public BaseResponse<String> sendEmailToStudent(SendEmailToStudentRequest request) {
        try{
            EmailRequest emailRequest=new EmailRequest();
            emailRequest.setSubject(request.getLectureName()+"课程开课通知");
            emailRequest.setBody(request.getStudentName()+"你好，欢迎报名参加本次课程，该课程即将开课，请注意及时报道");
            emailRequest.setTo(request.getEmail());
            emailService.sendEmail(emailRequest);
            return new BaseResponse<>("发送成功！",true,"发送成功");
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),true,"发送失败！");
        }
    }

    //新增网站通知
    public BaseResponse<Notification> sendWebNotification(CreateWebNoticeRequest request) {
        try{
            String content=new String("各位学员大家好！浩奇公司的"+request.getLectureName()+
                    "将于"+request.getBeginTime()+"在"+request.getLecturePlace()+"进行，请各位学员准时参加");

            Notification notification=new Notification();
            notification.setNotifyContent(content);

            //对应的课程是否发出通知，设置为true
            Optional<Lecture> lectureOptional=lectureRepository.findByIdAndDeletedFalse(request.getLectureId());
            if(lectureOptional.isPresent()){
                Lecture lecture=lectureOptional.get();
                lecture.setIsNotificated(true);
                lectureRepository.save(lecture);
            }
            BeanUtil.copyProperties(request,notification, CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.CREATE_SUCCESS,true,notificationRepository.save(notification));
        }catch (Exception e){
            return new BaseResponse<>(ConstUtil.CREATE_FAILED,false,null);
        }
    }

    //更新网站通知
    public BaseResponse<Notification> updateWebNotice(UpdateWebNoticeRequest request) {
        try{
            Optional<Notification> optionalNotification=notificationRepository.findByIdAndDeletedFalse(request.getId());
            if(!optionalNotification.isPresent()){
                return new BaseResponse<>("该通知不存在！",false,null);
            }
            Notification notification=optionalNotification.get();
            BeanUtil.copyProperties(request,notification,CopyOptions.create().setIgnoreNullValue(true));
            return new BaseResponse<>(ConstUtil.UPDATE_SUCESS,true,notificationRepository.save(notification));
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //删除网站通知
    public BaseResponse<String> delete(Long id) {
        try{
            Optional<Notification> optionalNotification = notificationRepository.findByIdAndDeletedFalse(id);
            if(!optionalNotification.isPresent()){
                return new BaseResponse<>(ConstUtil.DELETED_FALSE,false,"该通知不存在！");
            }
            Notification notification=optionalNotification.get();
            notification.setDeleted(true);
            notificationRepository.save(notification);
            return new BaseResponse<>(ConstUtil.DELETED_SUCCESS,true,"删除成功！");
        }catch (Exception e){
            return new BaseResponse<>(e.toString(),false,null);
        }
    }

    //查询列表
    public BaseResponse<List<Notification>> queryList(String lectureName
            , String betweenTime, String lecturePlace) {
        try {
            Specification<Notification> specification = (root, query, builder) -> {
                List<Predicate> predicates = new ArrayList<>();
                if (lectureName!= null && !lectureName.equals("")) {
                    String lectureNameLike = "%" + lectureName + "%";
                    predicates.add(builder.like(root.get("lectureName"), lectureNameLike));
                }
                if (lecturePlace != null && !lecturePlace.equals("")) {
                    String lecturePlaceLike = "%" + lecturePlace + "%";
                    predicates.add(builder.like(root.get("lecturePlace"), lecturePlaceLike));
                }
                if (betweenTime!= null && !betweenTime.equals("")) {
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                    Date beginTime = null;
                    Date endTime = null;
                    try {
                        beginTime = dateFormat.parse(betweenTime.substring(0, 10));
                        endTime = dateFormat.parse(betweenTime.substring(13));
                    } catch (ParseException e) {
                        // 处理日期解析异常
                        e.printStackTrace(); // 或者记录日志
                    }
                    predicates.add(builder.between(root.get("lectureTime"), beginTime, endTime));
                }
                predicates.add(builder.equal(root.get("deleted"), false));
                return builder.and(predicates.toArray(new Predicate[0]));
            };
            List<Notification> list = notificationRepository.findAll(specification);
            Collections.reverse(list);
            return new BaseResponse<>(ConstUtil.QUERY_SUCCESS, true, list);
        } catch (Exception e) {
            return new BaseResponse<>(e.toString(), false, null);
        }
    }
}
